package com.main.usermanagement.domain.user.repository.handler;

import com.main.usermanagement.domain.user.valueobject.Email;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Email.class)
public class EmailTypeHandler extends BaseTypeHandler<Email> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Email parameter, JdbcType jdbcType) throws SQLException {
        // 确保非null的Email值被正确设置到PreparedStatement中
        ps.setString(i, parameter.getValue());
    }

    @Override
    public Email getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return convertToEmail(value);
    }

    @Override
    public Email getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return convertToEmail(value);
    }

    @Override
    public Email getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return convertToEmail(value);
    }

    private Email convertToEmail(String value) throws SQLException {
        if (value == null) {
            return null; // 返回null，而不是无效的Email对象
        }
        try {
            return new Email(value); // 调用Email的构造函数进行校验
        } catch (IllegalArgumentException e) {
            // 如果数据库中的值不合法，抛出SQLException
            throw new SQLException("Invalid email address in database: " + value, e);
        }
    }
}